

import Foundation
import soapp
import Eelay




public protocol MoURLOwnerRealization{
    func handle(url:URL,resource:String) -> Bool
    func handleOpenUniversalLink(userActivity: NSUserActivity) ->Bool
    var plat:String{get}
    var hosts:[String]{get set}
    var schemes:[String]{get set}

}


public class ThisAppURLOwner{
    public static var scheme = "app"
    public static func handleOpenUniversalLink(userActivity: NSUserActivity) ->Bool{
        
        if let url = userActivity.webpageURL{
            if (!url.absoluteString.hasPrefix("\(SDKConfig.WX.universalLink)\(SDKConfig.WX.appID)")){
                
                AppLink.open(link: url.absoluteString)
            }
        }
        return true
    }

    public static var openThisTask:(_ path:String, _ url:URL) -> Void = {path,_
         in
        AppLink.open(path, model: nil)
//         AppLink.open(link: path)
    }
    static public func handle(url: URL, resource: String) -> Bool {
        let regstr = "^\(scheme)://[^/]+/"
        do{
            let reg = try Regex(string: regstr)
            let action = url.absoluteString.replacingAll(matching: reg, with: "")
            openThisTask(action,url)
        }
        catch{
                       
        }
        return true
    }
}


public class HandleOpenURL:NSObject{
    
    public static let shared = HandleOpenURL()
    public static var urlOwners = [MoURLOwnerRealization]()
    public static func add(owner:MoURLOwnerRealization){
        if let _ = getOwner(plat: owner.plat){
            return
        }
        urlOwners.append(owner)
    }
    public static func getOwner(plat:String)->MoURLOwnerRealization?{
        for plat_ in urlOwners {
            if plat == plat_.plat{
                return plat_
            }
        }
        
        return nil
    }
    
    
    public func handleOpenUniversalLink(userActivity: NSUserActivity) ->Bool{
       
        _ = ThisAppURLOwner.handleOpenUniversalLink(userActivity: userActivity)
        var ok = true
        for owner in HandleOpenURL.urlOwners {
            ok = owner.handleOpenUniversalLink(userActivity: userActivity)
        }
        return ok
    }
    
    public func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

        let urlResource = options[UIApplication.OpenURLOptionsKey.sourceApplication]
//        [[MEShareCenter defaultCenter] tellShareResult:dict];
        print("+++++urlOwners\(HandleOpenURL.urlOwners)")
        
        var url_ = urlResource as? String
        if url_ == nil{
            url_ = url.absoluteString
        }
        print("00000iiii",url.scheme)
        
        
//        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
        guard let  resourceStr = url_ else {
            return true
        }
        
//        let urlStr = url.absoluteString
//        print("+++++Sssds\(urlStr)")

       
        
        for owner in HandleOpenURL.urlOwners {
            if owner.hosts.contains(resourceStr){
                print("00000000---\(owner)")
                return owner.handle(url: url, resource: resourceStr)
            }
            if let scheme = url.scheme{
                if owner.schemes.contains(scheme){
                    print("00000000-sss--\(owner)")
                    return owner.handle(url: url, resource: resourceStr)
                }
            }
        
        }
        for owner in HandleOpenURL.urlOwners {
            
            print("------S|\(owner)")
            if let host = url.host{
                print("--------ssS|\(owner.hosts)==\(host)")
                if owner.hosts.contains(host){
                    print("--------ssS|\(host)")
                    return owner.handle(url: url, resource: resourceStr)
                }
            }
        }
        
        if resourceStr.hasPrefix(ThisAppURLOwner.scheme){
            print("____)))0000",resourceStr)
            return ThisAppURLOwner.handle(url: url, resource: resourceStr)
        }
        
      
       
               
        
//
//        switch urlOwner {
//        case .App(path: let path):
//            URLOwner.openSelfTask(path,url)
//            return true
//        case .WX:
//            return WXApi.handleOpen(url, delegate: WXApiManager.shared())
//        case .QQ:
//            let ret = QQApiInterface.handleOpen(url, delegate: self)
//            let dict = NSMutableDictionary()
//            dict["paltformUrl"] = resourceStr
//            if ret{
//                dict["status"] = "YES"
//            }else{
//                dict["status"] = "NO"
//            }
//            MEShareCenter.default().tellShareResult(dict)
//            if TencentOAuth.canHandleOpen(url){
//                return TencentOAuth.handleOpen(url)
//            }
//        case .Sina:
//            _ = WeiboSDK.handleOpen(url, delegate: self)
//        case .Ali(let type):
////            print("=dd====uuuus|\(url.host)==\(resource)")
//            switch type{
//            case .pay:
//                AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (info) in
//                    if let dict = info?.mutable_dictionary
//                    {
////                        "收到阿里支付".alert()
//                        FastAliPay.shared.dealCallBack(result: dict)
//                    }
//                })
//            case .auth:
//                break
//            }
//        default:
//            return true
//        }
        
        return true
    }
}
